<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class InvitationApply extends Model
{
    use HasDateTimeFormatter;
    // use SoftDeletes;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    public $timestamps = true;

    protected $table = 'eb_invitation_apply';

    protected $fillable = [
        'id',
        'company_name',
        'name',
        'phone',
        'email',
        'speaker_id',
        'speaker_name',
        'status',
        'audit_time',
        'audit_desc',
        'user_id',
        'revoke_remark'
    ];

    public function speaker()
    {
        return $this->hasOne(Speaker::class, 'id', 'speaker_id');
    }


    /**
     * 邀约申请列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-26
     * @param [type] $where
     * @return void
     */
    public static function getInvitationApplyList($where)
    {
        $builderWhere = function ($query) use ($where) {
            // $query->where('status', 1);
            $query->where('user_id', userId());
            $query->whereNull('delete_time');

            if (isset($where['speaker_name']) && $where['speaker_name'] != '') {
                $query->where('speaker_name', 'like', '%' . $where['speaker_name'] . '%');
            }

            if (isset($where['datetime']) && $where['datetime'] != '') {
                $query->whereDate('create_time', $where['datetime']);
            }
        };

        $list = self::with(['speaker' => function ($query) {
            $query->select('id', 'title');
        }])->where($builderWhere)
            ->select(
                'id',
                'company_name',
                'name',
                'phone',
                'email',
                'speaker_id',
                'speaker_name',
                'status',
                'audit_time',
                'audit_desc',
                'create_time',
                'user_id',
                'revoke_remark'
            )
            ->orderBy('create_time', 'desc')
            ->paginate($where['limit']);
        return $list;
    }

    /**
     * 前端撤销邀约申请
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-12-16
     * @param [type] $payload
     * @return void
     */
    public static function setRevokeRemarks($payload)
    {
        $data = self::find($payload['id']);

        if (empty($data)) {
            return fail_message('未找到邀约申请');
        }

        $data->audit_desc = $payload['revoke_remark'];
        $data->audit_time = Carbon::now();
        $data->status = -2;
        $data->save();
    }
}
